﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using P2P_Backup.connections;
using P2P_Backup.tools.io;
using System.Threading;

namespace P2P_Backup
{
    public class ProgressArgs : EventArgs
    {
        public ProgressArgs(double progress, double speed)
        {
            this.progress = progress;
            this.speed = speed;
        }

        private double progress;
        private double speed;

        public double Progress
        {
            get { return progress; }
        }
        public double Speed
        {
            get { return speed; }
        }
    }

    public class ProgressReporter
    {
        Thread speedCalc;
        public double Speed = 0;
        public double Progress;
        public long Position;
        public archive.File File;

        public event EventHandler<FileConnectionArgs> Progressed;
        private StreamCopy streamCopy;
        public ProgressReporter(archive.File file,StreamCopy streamCopy)
        {
            this.File = file;
            this.streamCopy = streamCopy;
            this.streamCopy.Progessed += new EventHandler<SimpleProgressArgs>(streamCopy_Progessed);
        }

        public void Begin()
        {
            File.Status = archive.TransferStatus.InProgress;
            onProgress(0);
            speedCalc = new Thread(calculateSpeed);
            speedCalc.IsBackground = true;
            speedCalc.Start();
        }

        private void calculateSpeed()
        {
            DateTime prevTime = DateTime.Now;
            long prevPos = Position;
            while (speedCalc.ThreadState == ThreadState.Background)
            {
                Thread.Sleep(1000);
                double ms = (DateTime.Now - prevTime).TotalMilliseconds;
                long bytes = Position - prevPos;

                if (ms != 0)
                    Speed = Math.Round(bytes / ms / 1024, 2); 

                prevTime = DateTime.Now;
                prevPos = Position;
                onProgress(Position);
            }
        }
        private void streamCopy_Progessed(object sender, SimpleProgressArgs e)
        {
            onProgress(e.Position);
        }
        
        private void onProgress(long position)
        {
            if (position == -1) 
                File.Status = archive.TransferStatus.Failed;
            else 
                Progress = Math.Round((double)position / (double)File.Size * 100, 2);

            this.Position = position;            
            if (Progressed != null) Progressed(this, new FileConnectionArgs(File, Progress, Speed));
        }
        public void Done()
        {
            speedCalc.Abort();
            File.Status = archive.TransferStatus.Complete;
            onProgress(File.Size);            
        }
    }
}
